<script setup lang="ts">
import { onMounted, ref } from "vue";
import { formRules } from "./utils/rule";
import { FormProps } from "./utils/types";
import { ElUpload } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

import { ElDialog, UploadProps, UploadFile, ElMessage } from "element-plus";
import { uploadFileApi } from "@/api/common";

const validImageFormats = ["jpg", "jpeg", "png"]; //允许的文件后缀
//选择文件格式校验//并限制上传数量
const checkImageFormat = file => {
  const fileFormat = file.name.split(".").pop().toLowerCase(); // 获取文件格式
  if (!validImageFormats.includes(fileFormat)) {
    ElMessage({ type: "error", message: "图片格式必须为 jpg/jpeg/png" });
    faceList.value = []; //删除格式不符合的文件
    return false; // 阻止文件上传
  }

  noUpload.value = true; //设置为true阻止继续上传
  console.log(file.raw);
  // 创建一个新的 FormData 对象并添加文件
  const formData = new FormData();
  formData.append("file", file.raw);
  // 验证 FormData 的内容
  uploadFileApi(formData)
    .then(res => {
      // 将上传的文件路径保存到 formInline.image 属性中
      props.formInline.image = res.data;
    })
    .catch(err => {
      console.log("上传附件失败::::" + err);
    });
  return true; // 允许文件上传
};
const dialogImageUrl = ref(""); //预览图片路径
const dialogVisible = ref(false); //预览框可见
//删除
const handleRemove: UploadProps["onRemove"] = (file: UploadFile) => {
  noUpload.value = false;
};
//预览
const handlePictureCardPreview: UploadProps["onPreview"] = (
  file: UploadFile
) => {
  dialogImageUrl.value = file.url!;
  dialogVisible.value = true;
};

const faceList = ref([]); //图片列表
const noUpload = ref(false); //不再上传

const checkBannerImageFormat = file => {
  const fileFormat = file.name.split(".").pop().toLowerCase(); // 获取文件格式
  if (!validImageFormats.includes(fileFormat)) {
    ElMessage({ type: "error", message: "图片格式必须为 jpg/jpeg/png" });
    faceBannerList.value = []; //删除格式不符合的文件
    return false; // 阻止文件上传
  }

  noBannerUpload.value = true; //设置为true阻止继续上传
  // 创建一个新的 FormData 对象并添加文件
  const formData = new FormData();
  formData.append("file", file.raw);
  // 验证 FormData 的内容
  uploadFileApi(formData)
    .then(res => {
      // 将上传的文件路径保存到 formInline.image 属性中
      props.formInline.banner = res.data;
    })
    .catch(err => {
      console.log("上传banner失败::::" + err);
    });
  return true; // 允许文件上传
};
const dialogBannerImageUrl = ref(""); //预览图片路径
const dialogBannerVisible = ref(false); //预览框可见
//删除
const handleBannerRemove: UploadProps["onRemove"] = (file: UploadFile) => {
  noBannerUpload.value = false;
};
//预览
const handleBannerPictureCardPreview: UploadProps["onPreview"] = (
  file: UploadFile
) => {
  dialogBannerImageUrl.value = file.url!;
  dialogBannerVisible.value = true;
};

const faceBannerList = ref([]); //图片列表
const noBannerUpload = ref(false); //不再上传

const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({
    scriptName: "",
    image: "",
    writer: "",
    banner: "",
    brief: ""
  })
});

onMounted(() => {
  if (props.formInline.image) {
    //   判断
    faceList.value.push({ url: props?.formInline.image });
    noUpload.value = true;
  }
  if (props.formInline.banner) {
    //   判断
    faceBannerList.value.push({ url: props?.formInline.banner });
    noBannerUpload.value = true;
  }
});

const ruleFormRef = ref();
const newFormInline = ref(props.formInline);

function getRef() {
  return ruleFormRef.value;
}

defineExpose({ getRef });
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="newFormInline"
    :rules="formRules"
    label-width="82px"
  >
    <el-form-item label="剧本名称" prop="scriptName">
      <el-input
        v-model="newFormInline.scriptName"
        clearable
        class="!w-[180px]"
        placeholder="请输入剧本名称"
      />
    </el-form-item>
    <el-form-item label="剧本封面" prop="image" label-width="90px">
      <el-upload
        :class="{ disabled: noUpload }"
        :auto-upload="false"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-change="checkImageFormat"
        :on-remove="handleRemove"
        :limit="1"
        :file-list="faceList"
      >
        <el-icon v-if="faceList.length == 0">
          <Plus />
        </el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="预览图片" />
      </el-dialog>
    </el-form-item>
    <el-form-item label="作者" prop="writer">
      <el-input
        v-model="newFormInline.writer"
        clearable
        class="!w-[180px]"
        placeholder="请输入作者名称"
      />
    </el-form-item>
    <el-form-item label="简介" prop="brief">
      <el-input
        v-model="newFormInline.brief"
        class="!w-[480px] !h-[177px]"
        placeholder="Please input"
        show-word-limit
        type="textarea"
        :rows="8"
        maxlength="200"
      />
    </el-form-item>
    <el-form-item label="剧本横图" prop="banner" label-width="90px">
      <el-upload
        :class="{ disabled: noBannerUpload }"
        style="width: 48px; height: 270px"
        :auto-upload="false"
        list-type="picture-card"
        :on-preview="handleBannerPictureCardPreview"
        :on-change="checkBannerImageFormat"
        :on-remove="handleBannerRemove"
        :limit="1"
        :file-list="faceBannerList"
      >
        <el-icon v-if="faceBannerList.length == 0">
          <Plus />
        </el-icon>
      </el-upload>

      <el-dialog v-model="dialogBannerVisible">
        <img w-full :src="dialogBannerImageUrl" alt="预览图片" />
      </el-dialog>
    </el-form-item>
  </el-form>
</template>
<style>
.el-textarea__inner {
  resize: none;
}
</style>
<style scoped>
::v-deep .disabled .el-upload--picture-card {
  display: none !important;
}
</style>
